<?php
/**
 * Ora - 后台产品管理模块
 * @author lan7
 * @copyright lan7.net
 * @version 2.0
 */

if(!defined('IN_ORA')) {
	exit('Access Denied');
}
class admin_case extends mod {

	/**
	 * 构造函数
	 *
	 * @return admin_case
	 */
	function admin_case(){
		parent::__construct();
		session_start();
		$this->setTplDir(PUBLIC_PATH);
		$this->setMsgTpl("admin/msg.html");
		if(!isset($_SESSION[$GLOBALS['ora_cfg']['sess_prefix']."admin"])){
			$this->showMsg("请先登录!",parse_uri("common-login"),1);
		}
	}

	/**
	 * 产品列表页
	 *
	 */
	function index(){
		$pid = is_numeric($GLOBALS['_param']['p'])?$GLOBALS['_param']['p']:1;
		$psize = $GLOBALS['_param']['psize']?$GLOBALS['_param']['psize']:$GLOBALS['ora_cfg']['page_size'];
		$total = $this->db->count("select count(*) from ".tn('product'));
		import("lib.page");
		$pobj = new page('p',$pid,$total,$psize);
		$sql = "select op.Id,op.pro_name,op.vod_id,oc.cat_name,op.pro_pic,op.pro_status,op.pro_views,op.pro_dateline from ".tn("product")." op";
		$sql .=" inner join (select Id from ".tn("product")." order by Id desc limit $pobj->sqlParam) b using(Id)  left join ".tn('cat')." oc on op.cat_id = oc.Id  order by op.Id desc";
		if($pobj->rsort){
			$sql = "select op.Id,op.pro_name,op.vod_id,oc.cat_name,op.pro_pic,op.pro_status,op.pro_views,op.pro_dateline from ".tn("product")." op";
			$sql .=" inner join (select Id from ".tn("product")." order by Id asc limit $pobj->sqlParam) b using(Id)  left join ".tn('cat')." oc on op.cat_id = oc.Id order by op.Id desc";
		}
		$pros = $this->db->getAll($sql);
		$this->assign("pobj",$pobj);
		$this->assign("pros",$pros);
		$this->assign('url',preg_replace('/\-?p(\-|_|\=)\d+/i',"",get_urlStr()));
		$this->display("admin/case.html");
	}

	/**
	 * 产品新增
	 *
	 */
	function add(){
		/* 获取类别 */
		import("lib.cat");
		$this->assign('cats',cat_lib::getSubChild(0,3,' and cat_type = 1 '));
		$id = $GLOBALS['_param']['id'];
		if(is_numeric($id)&&$id > 0){
			//修改产品
			import("lib.pro");
			$this->assign("pro",pro_lib::getPro($id,1,1,1));
		}
		$this->assign("vods",$this->db->getAll("select Id,v_title from ".tn('vod')." order by Id desc"));
		$this->assign("ptpl",getTpl());
		$this->display("admin/case.html");
	}

	/**
	 * 产品编辑
	 *
	 */
	function modify(){
		$this->add();
	}

	/**
	 * 新增或更新产品
	 *
	 */
	function save(){
		$id 		= intval($_POST["pro_id"]);
		$pro_name 	= clear_html($_POST["pro_name"]);
		$pro_keywords 	= clear_html($_POST["keywords"]);
		$pro_tags 		= clear_html($_POST["tags"]);
		$pro_link		= clear_html($_POST["pro_link"]);
		$pro_price		= clear_html($_POST["pro_price"]);
		$cat_id 	= is_numeric($_POST["cat_id"])?$_POST["cat_id"]:-1;
		$vod_id     = intval($_POST["vod_id"])>0?$_POST["vod_id"]:0;
		$content 	= $_POST["content"];
		/** 属性模板 **/
		$attrKey = $_POST["attrName"];
		$attrVal = $_POST["attrVal"];
		if($pro_name == ""){
			$this->showMsg("请输入产品名称!",$_SERVER["HTTP_REFERER"],1);
		}
		if($cat_id<0){
			$this->showMsg("请选择产品类别!",$_SERVER["HTTP_REFERER"],1);
		}
		if($content==""){
			$this->showMsg("请输入产品内容!",$_SERVER["HTTP_REFERER"],1);
		}
		/** TODO 添加内链 **/
		$content = htmlspecialchars($content);
		$pro_status = isset($_POST["pro_status"])?intval($_POST["pro_status"]):0;
		$pro_pic = $_POST["pro_pic"];
		$albumId = $_POST["albumId"];
		$coverImage = is_numeric($_POST["coverImage"])?$_POST["coverImage"]:-1;
		/** 图片 **/
		$picDesc = $_POST["uploadText"];
		/** 图片上传 **/
		$images = array();
		import("lib.image");
		import("lib.upload");
		$up = new Upload("jpg|gif|png");
		for ($j=0;$j<sizeof($up->files);$j++){
			$tmp = array();
			if($up->files[$j]['error'] == '0'){
				//上传成功的
				$tmp['url'] = $up->files[$j]['urlPath'];
				//添加图片描述信息
				$tmp['desc']= $picDesc[$j];
				//是否为封面图片
				$tmp['cover']= 0;
				if($j==$coverImage){
					$tmp['cover']= 1;
					$pro_pic = $tmp["url"];
				}
				//生成缩略图
				image::thumb(UPLOAD_PATH.$tmp['url'],'',$GLOBALS['ora_cfg']['thumb_width'],$GLOBALS['ora_cfg']['thumb_height']);
				$images[] = $tmp;
			}
		}
		if($coverImage == -1){
			if(!empty($images)){
				$pro_pic = $images[0]['url'];
				//默认取第一张图片为封面图片
				$images[0]['cover'] = 1;
			}
		}else if(!empty($albumId)){
			$result = $this->db->getOne("select pic from ".tn("album")." where Id = ".$albumId[0]);
			$pro_pic = $result['pic'];
		}

		if($id<=0){
			//新增
			$sql = "insert into ".tn("product")."(cat_id,pro_name,pro_keywords,pro_pic,pro_status,pro_tags,pro_dateline,pro_link,pro_price,vod_id)";
			$sql .=" values($cat_id,'$pro_name','$pro_keywords','$pro_pic',$pro_status,'$pro_tags',".time().",'".$pro_link."',$pro_price,$vod_id)";
			if(!$this->db->execute($sql)){
				/** 清除上传 **/
				foreach ($images as $v) {
					io::remove(ROOT_PATH.$v['url']);//大图
					io::remove(ROOT_PATH.time($v['url']));//缩略图
				}
				$this->showMsg("新增失败!",$_SERVER["HTTP_REFERER"],1);
			}
			$id = $this->db->getLastInsId();
		}else{
			//修改
			$sql = "update ".tn("product")." set pro_link='$pro_link',pro_price=$pro_price,cat_id = $cat_id,pro_name = '$pro_name',pro_keywords = '$pro_keywords' ,";
			$sql .=" pro_pic = '$pro_pic',pro_tags='$pro_tags',pro_status = $pro_status,pro_dateline =  ".time().",vod_id = $vod_id where Id = $id";
			if(!$this->db->execute($sql)){
				foreach ($images as $v) {
					io::remove(ROOT_PATH.$v['url']);//大图
					io::remove(ROOT_PATH.time($v['url']));//缩略图
				}
				$this->showMsg("修改失败!",$_SERVER["HTTP_REFERER"],1);
			}
		}
		/** 内容处理 **/
		$this->db->execute("delete from ".tn("content")." where ctype=1 and fk_id = $id");
		$this->db->execute("insert into ".tn("content")."(ctype,fk_id,content) values(1,$id,'$content')");

		/** 图片处理 **/

		//更新描述信息
		for ($j=0;$j<sizeof($albumId);$j++){
			if($coverImage == -1 || $coverImage == $j){
				$this->db->execute("update ".tn("album")." set cover = 0 where alb_type =1 and fk_id = $id  ");
				$this->db->execute("update ".tn("album")." set cover = 1,alb_des ='".msubstr($picDesc[$j],0,80)."' where Id=".$albumId[$j]);
				$coverImage = null;
			}else{
				$this->db->execute("update ".tn("album")." set alb_des = '".msubstr($picDesc[$j],0,80)."' where Id = ".$albumId[$j]);
			}
		}
		if(is_array($albumId)&&!empty($albumId)){
			$albumIdstr = implode(",",$albumId);
		}else{
			$albumIdstr = 0;
		}
		$this->db->execute("delete from ".tn("album")." where alb_type = 1 and fk_id = $id and id not in ($albumIdstr)");
		foreach ($images as $k => $v){
			$sql  = "insert into ".tn("album")."(alb_name,alb_type,fk_id,pic,alb_des,alb_date,cover) ";
			$sql .= " values('$pro_name',1,$id,'{$v['url']}','{$picDesc[sizeof($albumId)+$k]}',".time().",{$v['cover']})";
			$this->db->execute($sql);
		}

		/** 标签处理 **/
		$this->db->execute("delete from ".tn("tags")." where tag_type = 1 and  fk_id = $id");
		$pro_tags = explode(",",$pro_tags);
		if(!empty($pro_tags)){
			foreach ($pro_tags as $v) {
				if($v!=""){
					$this->db->execute("insert into ".tn("tags")."(tag_type,fk_id,tag_name) values(1,$id,'$v')");
				}
			}
		}
		/** 属性处理 **/
		$attr = array();
		if(!empty($attrKey)&&!empty($attrVal)){
			$tmp = array();
			$tmp["key"] = $attrKey;
			$tmp["val"] = $attrVal;
			$attr = $tmp;
		}
		$attrStr = serialize($attr);
		$this->db->execute("delete from ".tn("pattr")." where p_id = $id");
		$this->db->execute("insert into ".tn("pattr")."(p_id,attr) values($id,'$attrStr')");
		$this->showMsg("操作成功!",parse_uri("admin_case-index|true"),1);
	}

	/**
	 * 产品删除
	 *
	 */
	function del(){
		$id = isset($GLOBALS['_param']['id'])?$GLOBALS['_param']['id']:$_POST["id"];
		if(is_array($id)){
			$idstr = implode(",",$id);
			$this->db->execute("delete from ".tn("content")." where ctype=1 and fk_id in($idstr)");
			/** 删除属性 **/
			$this->db->execute("delete from ".tn("pattr")." where p_id in ($idstr)");
			/** 删除图集 **/
			$pics = $this->db->getAll("select pic from  ".tn("album")." where alb_type = 1 and fk_id in ($idstr)");
			/** 删除图片文件 **/
			for ($i=0;$i<sizeof($pics);$i++){
				io::remove(ROOT_PATH.$pics[$i]["pic"]);
				io::remove(ROOT_PATH.timg($pics[$i]["pic"]));
			}
			$this->db->execute("delete from ".tn("album")." where alb_type = 1 and fk_id in ( $idstr)");
			$this->db->execute("delete from ".tn("product")." where Id in ( $idstr)");
			/** 删除标签 **/
			$this->db->execute("delete from ".tn("tags")." where tag_type = 1 and fk_id in ( $idstr)");

		}else{
			$id = intval($id);
			if($id>0){
				/** 删除内容 **/
				$this->db->execute("delete from ".tn("content")." where ctype=1 and fk_id = $id");
				/** 删除属性 **/
				$this->db->execute("delete from ".tn("pattr")." where p_id = $id");
				/** 删除图集 **/
				$pics = $this->db->getAll("select pic from  ".tn("album")." where alb_type = 1 and fk_id = $id");
				/** 删除图片文件 **/
				for ($i=0;$i<sizeof($pics);$i++){
					io::remove(UPLOAD_PATH.$pics[$i]["pic"]);
					io::remove(UPLOAD_PATH.timg($pics[$i]["pic"]));
				}
				$this->db->execute("delete from ".tn("album")." where alb_type = 1 and fk_id = $id");
				$this->db->execute("delete from ".tn("product")." where Id = $id");
				/** 删除标签 **/
				$this->db->execute("delete from ".tn("tags")." where tag_type = 1 and fk_id =  $id ");
			}
		}
		$this->showMsg("操作成功!",parse_uri("admin_case-index|true"),1);
	}

	/** 审核产品 **/
	function pass(){
		$id = $_POST["id"];
		if($id!=""&&is_array($id)){
			$id = array_filter($id,"filt");
			$this->db->execute("update ".tn("product")." set pro_status = 1 where Id in (".implode(",",$id).")");
			$this->showMsg("审核成功!",parse_uri("admin_case-index"),1);
		}
		$this->showMsg("请选择待审核的产品!",parse_uri("admin_case-index"),1);
	}
	/** 推荐文章 **/
	function recommend(){
		$id = $_POST["id"];
		if($id!=""&&is_array($id)){
			$id = array_filter($id,"filt");
			$this->db->execute("update ".tn("product")." set pro_status = 2 where Id in (".implode(",",$id).")");
			$this->showMsg("操作成功!",parse_uri("admin_case-index"),1);
		}
		$this->showMsg("请选择待推荐的产品!",parse_uri("admin_article-index"),1);
	}
}


//////////////////////////////////////////
/** 获取类型模板 **/
function getTpl(){
	$result = array();
	$query = $GLOBALS['db']->query("select * from ".tn("ptpl")." order by Id desc");
	while ($row = $GLOBALS['db']->fetch_array($query)) {
		$row['tpl'] = unserialize($row['tpl']);
		$result[] = $row;
	}
	return $result;
}
/** 过滤非数字元素 **/
function filt($v){
	return is_numeric($v);
}
?>